// 全局状态
let state = {
  groups: [],
  keywords: [],
  settings: {
    enabled: true,
    scanDelay: 300,
    regexSupport: false,
    tooltipTheme: 'dark',
    tooltipPosition: 'follow'
  },
  editingGroup: null,
  editingKeyword: null,
  selectedGroup: null,
  currentFilters: {
    group: '',
    search: '',
    sort: 'name'
  },
  batchKeywords: [] // 新增：批量添加的关键词预览
};

// DOM 元素
const elements = {
  // 标签页
  tabBtns: document.querySelectorAll('.tab-btn'),
  tabPanels: document.querySelectorAll('.tab-panel'),

  // 分组管理
  groupsList: document.getElementById('groups-list'),
  addGroupBtn: document.getElementById('add-group'),
  viewGroupKeywordsBtn: document.getElementById('view-group-keywords'),

  // 关键词管理
  keywordsList: document.getElementById('keywords-list'),
  addKeywordBtn: document.getElementById('add-keyword'),
  importKeywordsBtn: document.getElementById('import-keywords'),
  clearAllBtn: document.getElementById('clear-all'),
  keywordSearch: document.getElementById('keyword-search'),
  groupFilter: document.getElementById('group-filter'),
  sortKeywords: document.getElementById('sort-keywords'),
  keywordsStats: document.getElementById('keywords-stats'),

  // 设置
  toggleHighlightBtn: document.getElementById('toggle-highlight'),
  scanDelayInput: document.getElementById('scan-delay'),
  regexSupportCheckbox: document.getElementById('regex-support'),
  storageUsed: document.getElementById('storage-used'),
  storageText: document.getElementById('storage-text'),
  exportDataBtn: document.getElementById('export-data'),
  importDataBtn: document.getElementById('import-data'),
  tooltipTheme: document.getElementById('tooltip-theme'),
  tooltipPosition: document.getElementById('tooltip-position'),

  // 模态框
  groupModal: document.getElementById('group-modal'),
  keywordModal: document.getElementById('keyword-modal'),

  // 分组模态框元素
  groupModalTitle: document.getElementById('group-modal-title'),
  groupNameInput: document.getElementById('group-name'),
  groupColorInput: document.getElementById('group-color'),
  saveGroupBtn: document.getElementById('save-group'),
  cancelGroupBtn: document.getElementById('cancel-group'),

  // 关键词模态框元素
  keywordModalTitle: document.getElementById('keyword-modal-title'),
  keywordGroupSelect: document.getElementById('keyword-group'),
  keywordTextInput: document.getElementById('keyword-text'),
  keywordTipInput: document.getElementById('keyword-tip'),
  saveKeywordBtn: document.getElementById('save-keyword'),
  cancelKeywordBtn: document.getElementById('cancel-keyword'),

  // 批量添加关键词
  batchKeywordModal: document.getElementById('batch-keyword-modal'),
  batchKeywordGroup: document.getElementById('batch-keyword-group'),
  batchKeywordText: document.getElementById('batch-keyword-text'),
  batchKeywordTip: document.getElementById('batch-keyword-tip'),
  batchAddKeywordBtn: document.getElementById('batch-add-keyword'),
  saveBatchKeywordBtn: document.getElementById('save-batch-keyword'),
  cancelBatchKeywordBtn: document.getElementById('cancel-batch-keyword'),
  batchPreview: document.getElementById('batch-preview'),
  previewCount: document.getElementById('preview-count'),
  previewList: document.getElementById('preview-list'),
  batchStats: document.getElementById('batch-stats')
};

// 初始化应用
function initApp() {
  loadData();
  setupEventListeners();
  renderGroups();
  renderKeywords();
  updateStorageInfo();
  updateGroupFilter();
  updateViewGroupButton();
  // 初始化批量添加的分组选择
  updateBatchGroupSelect();
  isActiveTab();
  updateActiveTabsList()
}

// 加载数据
function loadData() {
  chrome.storage.local.get(['groups', 'keywords', 'settings', 'filters'], (result) => {
    if (result.groups) state.groups = result.groups;
    if (result.keywords) state.keywords = result.keywords;
    if (result.settings) state.settings = {...state.settings, ...result.settings};
    if (result.filters) state.currentFilters = {...state.currentFilters, ...result.filters};

    // 更新UI
    updateToggleButton();
    elements.scanDelayInput.value = state.settings.scanDelay;
    elements.regexSupportCheckbox.checked = state.settings.regexSupport;
    if (elements.tooltipTheme) elements.tooltipTheme.value = state.settings.tooltipTheme || 'dark';
    if (elements.tooltipPosition) elements.tooltipPosition.value = state.settings.tooltipPosition || 'follow';

    renderGroups();
    renderKeywords();
    updateStorageInfo();
    updateGroupFilter();
  });
}

// 保存数据
function saveData() {
  chrome.storage.local.set({
    groups: state.groups,
    keywords: state.keywords,
    settings: state.settings,
    filters: state.currentFilters
  }, () => {
    updateStorageInfo();
    // 通知content script更新高亮
    chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
      if (tabs[0]) {
        chrome.tabs.sendMessage(tabs[0].id, {
          action: 'updateHighlight',
          groups: state.groups,
          keywords: state.keywords,
          settings: state.settings
        });
      }
    });
  });
}

// 设置事件监听器
function setupEventListeners() {
  // 标签页切换
  elements.tabBtns.forEach(btn => {
    btn.addEventListener('click', () => {
      const tab = btn.dataset.tab;
      switchTab(tab);
    });
  });

  // 分组管理
  elements.addGroupBtn.addEventListener('click', () => openGroupModal());
  elements.saveGroupBtn.addEventListener('click', saveGroup);
  elements.cancelGroupBtn.addEventListener('click', closeGroupModal);
  elements.viewGroupKeywordsBtn.addEventListener('click', viewGroupKeywords);

  // 关键词管理
  elements.addKeywordBtn.addEventListener('click', () => openKeywordModal());
  elements.saveKeywordBtn.addEventListener('click', saveKeyword);
  elements.cancelKeywordBtn.addEventListener('click', closeKeywordModal);
  elements.importKeywordsBtn.addEventListener('click', importKeywords);
  elements.clearAllBtn.addEventListener('click', clearAllKeywords);
  elements.keywordSearch.addEventListener('input', renderKeywords);
  elements.groupFilter.addEventListener('change', renderKeywords);
  elements.sortKeywords.addEventListener('change', renderKeywords);

  // 批量添加关键词
  elements.batchAddKeywordBtn.addEventListener('click', () => openBatchKeywordModal());
  elements.saveBatchKeywordBtn.addEventListener('click', saveBatchKeywords);
  elements.cancelBatchKeywordBtn.addEventListener('click', closeBatchKeywordModal);
  elements.batchKeywordText.addEventListener('input', updateBatchPreview);
  elements.batchKeywordText.addEventListener('paste', handleBatchPaste);

  // 设置
  elements.toggleHighlightBtn.addEventListener('click', toggleHighlight);
  elements.scanDelayInput.addEventListener('change', updateSettings);
  elements.regexSupportCheckbox.addEventListener('change', updateSettings);
  elements.exportDataBtn.addEventListener('click', exportData);
  elements.importDataBtn.addEventListener('click', importData);
  if (elements.tooltipTheme) elements.tooltipTheme.addEventListener('change', updateTooltipSettings);
  if (elements.tooltipPosition) elements.tooltipPosition.addEventListener('change', updateTooltipSettings);

  // 模态框关闭
  document.querySelectorAll('.close-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      elements.groupModal.classList.remove('active');
      elements.keywordModal.classList.remove('active');
      elements.batchKeywordModal.classList.remove('active');
    });
  });

  // 点击模态框外部关闭
  window.addEventListener('click', (e) => {
    if (e.target === elements.groupModal) {
      elements.groupModal.classList.remove('active');
    }
    if (e.target === elements.keywordModal) {
      elements.keywordModal.classList.remove('active');
    }
    if (e.target === elements.batchKeywordModal) {
      elements.batchKeywordModal.classList.remove('active');
    }
  });
}

// 打开批量添加关键词模态框
function openBatchKeywordModal() {
  // 更新分组选择框
  updateBatchGroupSelect();

  // 清空输入
  elements.batchKeywordText.value = '';
  elements.batchKeywordTip.value = '';

  // 隐藏预览
  elements.batchPreview.style.display = 'none';
  state.batchKeywords = [];

  elements.batchKeywordModal.classList.add('active');
  elements.batchKeywordText.focus();
}

// 关闭批量添加关键词模态框
function closeBatchKeywordModal() {
  elements.batchKeywordModal.classList.remove('active');
  state.batchKeywords = [];
}

// 更新批量添加的分组选择框
function updateBatchGroupSelect() {
  elements.batchKeywordGroup.innerHTML = state.groups.map(group =>
      `<option value="${group.id}">${group.name}</option>`
  ).join('');

  if (state.groups.length === 0) {
    elements.batchKeywordGroup.innerHTML = '<option value="">暂无分组</option>';
  }
}

// 更新批量添加预览
function updateBatchPreview() {
  const text = elements.batchKeywordText.value.trim();

  if (!text) {
    elements.batchPreview.style.display = 'none';
    state.batchKeywords = [];
    return;
  }

  // 解析关键词
  const keywords = parseBatchKeywords(text);
  state.batchKeywords = keywords;

  // 更新预览
  updatePreviewDisplay(keywords);
}

// 处理粘贴事件
function handleBatchPaste(e) {
  // 允许粘贴完成
  setTimeout(() => {
    updateBatchPreview();
  }, 0);
}

// 解析批量关键词
function parseBatchKeywords(text) {
  // 使用正则表达式分割：支持空格、逗号、分号、换行等分隔符
  const separators = /[\s,，;；、\n\r]+/;
  const rawKeywords = text.split(separators);

  // 过滤空字符串和重复项，并统计状态
  const seen = new Set();
  const keywords = [];

  let newCount = 0;
  let duplicateCount = 0;
  let existingCount = 0;

  rawKeywords.forEach(keyword => {
    const trimmed = keyword.trim();
    if (!trimmed) return;

    // 检查是否已存在（在当前批量输入中）
    if (seen.has(trimmed)) {
      duplicateCount++;
      keywords.push({
        text: trimmed,
        status: 'duplicate' // 在当前批量输入中重复
      });
      return;
    }

    seen.add(trimmed);

    // 检查是否已存在于数据库中
    const existsInDb = state.keywords.some(k => k.text === trimmed);

    if (existsInDb) {
      existingCount++;
      keywords.push({
        text: trimmed,
        status: 'existing' // 在数据库中已存在
      });
    } else {
      newCount++;
      keywords.push({
        text: trimmed,
        status: 'new' // 新关键词
      });
    }
  });

  // 更新统计信息
  updateBatchStats(newCount, duplicateCount, existingCount);

  return keywords;
}

// 更新批量添加统计信息
function updateBatchStats(newCount, duplicateCount, existingCount) {
  elements.batchStats.innerHTML = `
    <span class="stat-new">新增: ${newCount}</span>
    <span class="stat-existing">已存在: ${existingCount}</span>
    <span class="stat-duplicate">重复: ${duplicateCount}</span>
  `;
}

// 更新预览显示
function updatePreviewDisplay(keywords) {
  elements.previewCount.textContent = keywords.filter(k => k.status === 'new').length;

  if (keywords.length === 0) {
    elements.previewList.innerHTML = '<div class="preview-item">暂无有效关键词</div>';
  } else {
    elements.previewList.innerHTML = keywords.map(keyword => {
      let className = 'preview-item';
      let icon = 'check';

      if (keyword.status === 'duplicate') {
        className += ' duplicate-keyword';
        icon = 'content_copy';
      } else if (keyword.status === 'existing') {
        className += ' existing-keyword';
        icon = 'info';
      }

      return `
        <div class="${className}">
          <span class="material-icons" style="font-size: 14px;">${icon}</span>
          ${keyword.text}
        </div>
      `;
    }).join('');
    elements.batchStats.style.display = 'flex';
  }

  elements.batchPreview.style.display = 'block';
}

// 保存批量关键词
function saveBatchKeywords() {
  const groupId = elements.batchKeywordGroup.value;
  const tip = elements.batchKeywordTip.value.trim();

  if (!groupId) {
    alert('请选择分组');
    return;
  }

  // 只保存状态为"new"的关键词
  const newKeywords = state.batchKeywords.filter(k => k.status === 'new');

  if (newKeywords.length === 0) {
    alert('没有可添加的新关键词');
    return;
  }

  // 添加到关键词列表
  newKeywords.forEach(keyword => {
    state.keywords.push({
      id: generateId(),
      text: keyword.text,
      tip: tip,
      groupId: groupId,
      createdAt: new Date().toISOString(),
      matchCount: 0
    });
  });

  saveData();
  renderKeywords();
  renderGroups();
  closeBatchKeywordModal();

  alert(`成功添加 ${newKeywords.length} 个关键词`);
}

// 切换标签页
function switchTab(tabName) {
  // 更新标签按钮状态
  elements.tabBtns.forEach(btn => {
    btn.classList.toggle('active', btn.dataset.tab === tabName);
  });

  // 更新标签面板状态
  elements.tabPanels.forEach(panel => {
    panel.classList.toggle('active', panel.id === `${tabName}-tab`);
  });

  // 如果是关键词标签，更新分组选择框
  if (tabName === 'keywords') {
    updateGroupSelect();
    updateBatchGroupSelect(); // 新增这行
  }

}

// 渲染分组列表
function renderGroups() {
  if (state.groups.length === 0) {
    elements.groupsList.innerHTML = `
      <div class="empty-state">
        <span class="material-icons">folder_open</span>
        <p>暂无分组，点击"新建分组"开始添加</p>
      </div>
    `;
    return;
  }

  elements.groupsList.innerHTML = state.groups.map(group => `
    <div class="group-card ${state.selectedGroup === group.id ? 'selected' : ''}" data-id="${group.id}">
      <div class="group-info">
        <div class="group-color" style="background-color: ${group.color}"></div>
        <div>
          <div class="group-name">${group.name}</div>
          <div class="group-keywords">${getGroupKeywordCount(group.id)} 个关键词</div>
        </div>
      </div>
      <div class="group-actions">
        <button class="icon-btn edit-group" data-id="${group.id}">
          <span class="material-icons">edit</span>
        </button>
        <button class="icon-btn delete-group" data-id="${group.id}">
          <span class="material-icons">delete</span>
        </button>
      </div>
    </div>
  `).join('');

  // 添加分组卡片点击事件
  document.querySelectorAll('.group-card').forEach(card => {
    card.addEventListener('click', (e) => {
      // 防止点击操作按钮时触发
      if (e.target.closest('.group-actions')) return;

      const groupId = card.dataset.id;
      toggleGroupSelection(groupId);
    });
  });

  // 添加分组操作事件监听器
  document.querySelectorAll('.edit-group').forEach(btn => {
    btn.addEventListener('click', (e) => {
      const groupId = e.currentTarget.dataset.id;
      openGroupModal(groupId);
    });
  });

  document.querySelectorAll('.delete-group').forEach(btn => {
    btn.addEventListener('click', (e) => {
      const groupId = e.currentTarget.dataset.id;
      deleteGroup(groupId);
    });
  });
}

// 切换分组选中状态
function toggleGroupSelection(groupId) {
  if (state.selectedGroup === groupId) {
    // 取消选中
    state.selectedGroup = null;
  } else {
    // 选中新分组
    state.selectedGroup = groupId;
  }

  // 更新查看按钮状态
  updateViewGroupButton();

  // 重新渲染分组列表以更新选中状态
  renderGroups();
}

// 更新查看组内关键词按钮状态
function updateViewGroupButton() {
  if (elements.viewGroupKeywordsBtn) {
    elements.viewGroupKeywordsBtn.disabled = !state.selectedGroup;
  }
}

// 查看组内关键词
function viewGroupKeywords() {
  if (!state.selectedGroup) return;

  // 切换到关键词管理标签
  switchTab('keywords');

  // 设置分组筛选器
  elements.groupFilter.value = state.selectedGroup;
  state.currentFilters.group = state.selectedGroup;

  // 渲染关键词列表
  renderKeywords();
}

// 渲染关键词列表
function renderKeywords() {
  const searchTerm = elements.keywordSearch.value.toLowerCase();
  const groupFilter = elements.groupFilter.value;
  const sortBy = elements.sortKeywords.value;

  // 更新筛选状态
  state.currentFilters = {
    search: searchTerm,
    group: groupFilter,
    sort: sortBy
  };

  let filteredKeywords = [...state.keywords];

  // 应用文本搜索筛选
  if (searchTerm) {
    filteredKeywords = filteredKeywords.filter(keyword =>
        keyword.text.toLowerCase().includes(searchTerm) ||
        keyword.tip.toLowerCase().includes(searchTerm)
    );
  }

  // 应用分组筛选
  if (groupFilter) {
    filteredKeywords = filteredKeywords.filter(keyword => keyword.groupId === groupFilter);
  }

  // 应用排序
  filteredKeywords.sort((a, b) => {
    switch (sortBy) {
      case 'name':
        return a.text.localeCompare(b.text);
      case 'group':
        const groupA = state.groups.find(g => g.id === a.groupId)?.name || '';
        const groupB = state.groups.find(g => g.id === b.groupId)?.name || '';
        return groupA.localeCompare(groupB);
      case 'date':
        return new Date(b.createdAt) - new Date(a.createdAt);
      default:
        return 0;
    }
  });

  // 渲染关键词统计
  renderKeywordsStats(filteredKeywords);

  if (filteredKeywords.length === 0) {
    let emptyMessage = '暂无关键词，点击"添加关键词"开始添加';

    if (searchTerm || groupFilter) {
      emptyMessage = '没有找到匹配的关键词';
      if (searchTerm && groupFilter) {
        const groupName = getGroupName(groupFilter);
        emptyMessage = `在"${groupName}"分组中没有找到包含"${searchTerm}"的关键词`;
      } else if (groupFilter) {
        const groupName = getGroupName(groupFilter);
        emptyMessage = `"${groupName}"分组中暂无关键词`;
      } else if (searchTerm) {
        emptyMessage = `没有找到包含"${searchTerm}"的关键词`;
      }
    }

    elements.keywordsList.innerHTML = `
      <div class="empty-state">
        <span class="material-icons">search</span>
        <p>${emptyMessage}</p>
        ${searchTerm || groupFilter ? '<button id="clear-filters" class="btn primary">清除筛选条件</button>' : ''}
      </div>
    `;

    // 添加清除筛选按钮事件
    const clearFiltersBtn = document.getElementById('clear-filters');
    if (clearFiltersBtn) {
      clearFiltersBtn.addEventListener('click', clearFilters);
    }

    return;
  }

  elements.keywordsList.innerHTML = filteredKeywords.map(keyword => {
    const group = state.groups.find(g => g.id === keyword.groupId);
    return `
      <div class="keyword-item">
        <div class="keyword-info">
          <div class="keyword-text">${keyword.text}</div>
          <div class="keyword-group" style="color: ${group ? group.color : '#5f6368'}">
            ${group ? group.name : '未分组'}
          </div>
          ${keyword.tip ? `<div class="keyword-tip">${keyword.tip}</div>` : ''}
        </div>
        <div class="group-actions">
          <button class="icon-btn edit-keyword" data-id="${keyword.id}">
            <span class="material-icons">edit</span>
          </button>
          <button class="icon-btn delete-keyword" data-id="${keyword.id}">
            <span class="material-icons">delete</span>
          </button>
        </div>
      </div>
    `;
  }).join('');

  // 添加关键词操作事件监听器
  document.querySelectorAll('.edit-keyword').forEach(btn => {
    btn.addEventListener('click', (e) => {
      const keywordId = e.currentTarget.dataset.id;
      openKeywordModal(keywordId);
    });
  });

  document.querySelectorAll('.delete-keyword').forEach(btn => {
    btn.addEventListener('click', (e) => {
      const keywordId = e.currentTarget.dataset.id;
      deleteKeyword(keywordId);
    });
  });
}

// 渲染关键词统计信息
function renderKeywordsStats(keywords) {
  if (keywords.length === 0 && !state.currentFilters.search && !state.currentFilters.group) {
    elements.keywordsStats.style.display = 'none';
    return;
  }

  elements.keywordsStats.style.display = 'flex';
  elements.keywordsStats.innerHTML = `
    <div class="stat-item">
      <div class="stat-value">${keywords.length}</div>
      <div class="stat-label">显示关键词</div>
    </div>
    <div class="stat-item">
      <div class="stat-value">${state.keywords.length}</div>
      <div class="stat-label">总关键词</div>
    </div>
    <div class="stat-item">
      <div class="stat-value">${state.groups.length}</div>
      <div class="stat-label">分组数量</div>
    </div>
  `;
}

// 获取分组名称
function getGroupName(groupId) {
  const group = state.groups.find(g => g.id === groupId);
  return group ? group.name : '未知分组';
}

// 清除筛选条件
function clearFilters() {
  // 重置搜索框
  elements.keywordSearch.value = '';

  // 重置分组筛选
  elements.groupFilter.value = '';

  // 重置排序
  elements.sortKeywords.value = 'name';

  // 重置筛选状态
  state.currentFilters = {
    search: '',
    group: '',
    sort: 'name'
  };

  // 重新渲染关键词列表
  renderKeywords();
}

// 更新分组筛选器选项
function updateGroupFilter() {
  if (!elements.groupFilter) return;

  elements.groupFilter.innerHTML = '<option value="">全部分组</option>' +
      state.groups.map(group =>
          `<option value="${group.id}">${group.name}</option>`
      ).join('');

  // 设置当前选中的分组
  if (state.currentFilters.group) {
    elements.groupFilter.value = state.currentFilters.group;
  }
}

// 打开分组模态框
function openGroupModal(groupId = null) {
  state.editingGroup = groupId ? state.groups.find(g => g.id === groupId) : null;

  if (state.editingGroup) {
    elements.groupModalTitle.textContent = '编辑分组';
    elements.groupNameInput.value = state.editingGroup.name;
    elements.groupColorInput.value = state.editingGroup.color;
  } else {
    elements.groupModalTitle.textContent = '新建分组';
    elements.groupNameInput.value = '';
    elements.groupColorInput.value = '#4285f4';
  }

  elements.groupModal.classList.add('active');
  elements.groupNameInput.focus();
}

// 关闭分组模态框
function closeGroupModal() {
  elements.groupModal.classList.remove('active');
  state.editingGroup = null;
}

// 保存分组
function saveGroup() {
  const name = elements.groupNameInput.value.trim();
  const color = elements.groupColorInput.value;

  if (!name) {
    alert('请输入分组名称');
    return;
  }

  if (state.editingGroup) {
    // 更新现有分组
    state.editingGroup.name = name;
    state.editingGroup.color = color;
  } else {
    // 创建新分组
    const newGroup = {
      id: generateId(),
      name,
      color,
      createdAt: new Date().toISOString()
    };
    state.groups.push(newGroup);
  }

  saveData();
  renderGroups();
  updateGroupFilter();
  updateGroupSelect();
  closeGroupModal();
}

// 删除分组
function deleteGroup(groupId) {
  if (!confirm('确定要删除这个分组吗？分组内的关键词也将被删除。')) {
    return;
  }

  // 删除分组
  state.groups = state.groups.filter(g => g.id !== groupId);

  // 删除该分组下的所有关键词
  state.keywords = state.keywords.filter(k => k.groupId !== groupId);

  // 如果删除的是当前选中的分组，清除选中状态
  if (state.selectedGroup === groupId) {
    state.selectedGroup = null;
    updateViewGroupButton();
  }

  saveData();
  renderGroups();
  renderKeywords();
  updateGroupFilter();
  updateGroupSelect();
}

// 打开关键词模态框
function openKeywordModal(keywordId = null) {
  state.editingKeyword = keywordId ? state.keywords.find(k => k.id === keywordId) : null;

  if (state.editingKeyword) {
    elements.keywordModalTitle.textContent = '编辑关键词';
    elements.keywordTextInput.value = state.editingKeyword.text;
    elements.keywordTipInput.value = state.editingKeyword.tip;
    elements.keywordGroupSelect.value = state.editingKeyword.groupId;
  } else {
    elements.keywordModalTitle.textContent = '添加关键词';
    elements.keywordTextInput.value = '';
    elements.keywordTipInput.value = '';
    elements.keywordGroupSelect.value = state.groups.length > 0 ? state.groups[0].id : '';
  }

  elements.keywordModal.classList.add('active');
  elements.keywordTextInput.focus();
}

// 关闭关键词模态框
function closeKeywordModal() {
  elements.keywordModal.classList.remove('active');
  state.editingKeyword = null;
}

// 保存关键词
function saveKeyword() {
  const text = elements.keywordTextInput.value.trim();
  const tip = elements.keywordTipInput.value.trim();
  const groupId = elements.keywordGroupSelect.value;

  if (!text) {
    alert('请输入关键词');
    return;
  }

  if (!groupId) {
    alert('请选择分组');
    return;
  }

  if (state.editingKeyword) {
    // 更新现有关键词
    state.editingKeyword.text = text;
    state.editingKeyword.tip = tip;
    state.editingKeyword.groupId = groupId;
  } else {
    // 创建新关键词
    const newKeyword = {
      id: generateId(),
      text,
      tip,
      groupId,
      createdAt: new Date().toISOString(),
      matchCount: 0
    };
    state.keywords.push(newKeyword);
  }

  saveData();
  renderKeywords();
  renderGroups();
  closeKeywordModal();
}

// 删除关键词
function deleteKeyword(keywordId) {
  if (!confirm('确定要删除这个关键词吗？')) {
    return;
  }

  state.keywords = state.keywords.filter(k => k.id !== keywordId);
  saveData();
  renderKeywords();
  renderGroups();
}

// 更新分组选择框
function updateGroupSelect() {
  elements.keywordGroupSelect.innerHTML = state.groups.map(group =>
      `<option value="${group.id}">${group.name}</option>`
  ).join('');

  if (state.groups.length === 0) {
    elements.keywordGroupSelect.innerHTML = '<option value="">暂无分组</option>';
  }
}

// 获取分组关键词数量
function getGroupKeywordCount(groupId) {
  return state.keywords.filter(k => k.groupId === groupId).length;
}

// 切换高亮功能
function toggleHighlight() {
  state.settings.enabled = !state.settings.enabled;
  saveData();
  updateToggleButton();
}

// 更新切换按钮状态
function updateToggleButton() {
  const btn = elements.toggleHighlightBtn;
  const icon = btn.querySelector('.material-icons');
  const text = btn.querySelector('span:last-child');

  if (state.settings.enabled) {
    btn.classList.add('active');
    icon.textContent = 'highlight';
    text.textContent = '已启用';
  } else {
    btn.classList.remove('active');
    icon.textContent = 'highlight_off';
    text.textContent = '已禁用';
  }
}

// 更新设置
function updateSettings() {
  state.settings.scanDelay = parseInt(elements.scanDelayInput.value) || 300;
  state.settings.regexSupport = elements.regexSupportCheckbox.checked;
  saveData();
}

// 更新工具提示设置
function updateTooltipSettings() {
  state.settings.tooltipTheme = elements.tooltipTheme.value;
  state.settings.tooltipPosition = elements.tooltipPosition.value;
  saveData();

  // 通知content script更新设置
  chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
    if (tabs[0]) {
      chrome.tabs.sendMessage(tabs[0].id, {
        action: 'updateSettings',
        settings: {
          tooltipTheme: state.settings.tooltipTheme,
          tooltipPosition: state.settings.tooltipPosition
        }
      });
    }
  });
}

// 批量导入关键词
function importKeywords() {
  const input = document.createElement('input');
  input.type = 'file';
  input.accept = '.txt,.csv,.json';

  input.onchange = e => {
    const file = e.target.files[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = event => {
      try {
        const content = event.target.result;
        let importedKeywords = [];

        if (file.name.endsWith('.json')) {
          // JSON 格式导入
          const data = JSON.parse(content);
          if (Array.isArray(data.keywords)) {
            importedKeywords = data.keywords;
          }
        } else {
          // 文本格式导入 (每行一个关键词)
          const lines = content.split('\n');
          importedKeywords = lines
              .filter(line => line.trim())
              .map(line => ({
                text: line.trim(),
                tip: '',
                groupId: state.groups.length > 0 ? state.groups[0].id : ''
              }));
        }

        if (importedKeywords.length > 0) {
          // 添加到现有关键词
          importedKeywords.forEach(keyword => {
            if (!state.keywords.some(k => k.text === keyword.text)) {
              state.keywords.push({
                id: generateId(),
                text: keyword.text,
                tip: keyword.tip || '',
                groupId: keyword.groupId || (state.groups.length > 0 ? state.groups[0].id : ''),
                createdAt: new Date().toISOString(),
                matchCount: 0
              });
            }
          });

          saveData();
          renderKeywords();
          renderGroups();
          alert(`成功导入 ${importedKeywords.length} 个关键词`);
        } else {
          alert('没有找到可导入的关键词');
        }
      } catch (error) {
        alert('导入失败：文件格式不正确');
      }
    };

    reader.readAsText(file);
  };

  input.click();
}

// 清空所有关键词
function clearAllKeywords() {
  if (!confirm('确定要清空所有关键词吗？此操作不可撤销。')) {
    return;
  }

  state.keywords = [];
  saveData();
  renderKeywords();
  renderGroups();
}

// 导出数据
function exportData() {
  const data = {
    groups: state.groups,
    keywords: state.keywords,
    settings: state.settings,
    exportDate: new Date().toISOString()
  };

  const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
  const url = URL.createObjectURL(blob);

  const a = document.createElement('a');
  a.href = url;
  a.download = `keyword-highlight-${new Date().toISOString().split('T')[0]}.json`;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
}

// 导入数据
function importData() {
  const input = document.createElement('input');
  input.type = 'file';
  input.accept = '.json';

  input.onchange = e => {
    const file = e.target.files[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = event => {
      try {
        const data = JSON.parse(event.target.result);

        if (!confirm('导入数据将覆盖现有数据，确定要继续吗？')) {
          return;
        }

        if (data.groups) state.groups = data.groups;
        if (data.keywords) state.keywords = data.keywords;
        if (data.settings) state.settings = {...state.settings, ...data.settings};

        saveData();
        renderGroups();
        renderKeywords();
        updateToggleButton();
        elements.scanDelayInput.value = state.settings.scanDelay;
        elements.regexSupportCheckbox.checked = state.settings.regexSupport;
        if (elements.tooltipTheme) elements.tooltipTheme.value = state.settings.tooltipTheme || 'dark';
        if (elements.tooltipPosition) elements.tooltipPosition.value = state.settings.tooltipPosition || 'follow';

        alert('数据导入成功');
      } catch (error) {
        alert('导入失败：文件格式不正确');
      }
    };

    reader.readAsText(file);
  };

  input.click();
}

// 更新存储信息
function updateStorageInfo() {
  chrome.storage.local.getBytesInUse(null, bytes => {
    const usedKB = (bytes / 1024).toFixed(2);
    const totalKB = (5 * 1024).toFixed(2); // Chrome扩展通常有5MB存储限制
    const percentage = (bytes / (5 * 1024 * 1024)) * 100;

    elements.storageUsed.style.width = `${percentage}%`;
    elements.storageText.textContent = `${usedKB} KB / ${totalKB} KB`;
  });
}

// 生成唯一ID
function generateId() {
  return Date.now().toString(36) + Math.random().toString(36).substr(2);
}

// 初始化应用
document.addEventListener('DOMContentLoaded', initApp);


const toggle = document.getElementById('activityToggle');
const tabsList = document.getElementById('activeTabsList');
async function isActiveTab() {


// 获取当前标签页
  const [currentTab] = await chrome.tabs.query({ active: true, currentWindow: true });

// 检查当前标签页是否已激活
  chrome.runtime.sendMessage({ action: 'checkStatus', tabId: currentTab.id }, (response) => {
    toggle.checked = response?.isActive || false;
  });

// 切换状态
  toggle.addEventListener('change', () => {
    chrome.runtime.sendMessage({
      action: 'toggleActivity',
      tabId: currentTab.id,
      enable: toggle.checked
    });
    updateActiveTabsList();
  });

}


// 更新活跃标签页列表
async function updateActiveTabsList() {
  const response = await chrome.runtime.sendMessage({ action: 'getActiveTabs' });
  tabsList.innerHTML = '';

  if (response?.length > 0) {
    const tabs = await chrome.tabs.query({});
    response.forEach(tabId => {
      const tab = tabs.find(t => t.id === tabId);
      if (tab) {
        const tabEl = document.createElement('div');
        tabEl.className = 'tab-item';
        tabEl.textContent = tab.title || `标签页 ${tabId}`;
        tabsList.appendChild(tabEl);
      }
    });
  } else {
    const tabEl = document.createElement('div');
    tabEl.className = 'empty-content';
    tabEl.textContent = '没有活跃页面';
    tabsList.appendChild(tabEl);
    //tabsList.innerHTML = '<p style="text-align: center;width: 100%;display: block;">没有活跃页面</p>';
  }
}